package com.xugui.thumb.services.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xugui.thumb.mapper.BlogMapper;
import com.xugui.thumb.pojo.entity.Blog;
import com.xugui.thumb.pojo.entity.User;
import com.xugui.thumb.pojo.vo.BlogVo;
import com.xugui.thumb.services.BlogService;
import com.xugui.thumb.services.ThumbService;
import com.xugui.thumb.services.UserService;
import com.xugui.thumb.utils.RedisKeyUtil;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements BlogService {

    private final UserService userService;

    private final ThumbService thumbService;

    private final RedisTemplate<String, Object> redisTemplate;

    /**
     * 根据 id 查询博客
     * @param blogId 博客 id
     * @param request 请求
     * @return 博客详情
     */
    @Override
    public BlogVo getBlogVOById(Long blogId, HttpServletRequest request) {
        Blog blog = this.getById(blogId);
        User loginUser = userService.getLoginUser(request);  // 获得当前登录用户
        return this.getBlogVO(blog, loginUser);   // 封装博客详情
    }

    @Override
    public BlogVo getBlogVO(Blog blog, User loginUser) {
        BlogVo blogVO = new BlogVo();
        BeanUtil.copyProperties(blog, blogVO);
        if (loginUser == null) {
            return blogVO;
        }
        // 当前用户是否给该博客点赞
        // Thumb thumb = Db.lambdaQuery(Thumb.class)
        //         .eq(Thumb::getBlogId, blog.getId())
        //         .eq(Thumb::getUserId, loginUser.getId())
        //        .one();

        // Thumb thumb = thumbService.lambdaQuery()
        //        .eq(Thumb::getBlogId, blog.getId())
        //        .eq(Thumb::getUserId, loginUser.getId())
        //        .one();

        // blogVO.setHasThumb(thumb != null);

        // 直接查询 Redis (userId) -> (blogId, thumbId)
        Boolean exist = thumbService.hasThumb(blog.getId(), loginUser.getId());
        blogVO.setHasThumb(exist);

        return blogVO;
    }

    /**
     * 获取博客列表
     * @param blogList 博客列表
     * @param request 请求
     * @return 博客列表
     */
    @Override
    public List<BlogVo> getBlogVOList(List<Blog> blogList, HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        Map<Long, Boolean> blogIdHasThumbMap = new HashMap<>();  // 记录博客被当前用户点赞（博客ID, 是否点赞）
        // if (ObjUtil.isNotEmpty(loginUser)) {
        //     Set<Long> blogIdSet = blogList.stream().map(Blog::getId).collect(Collectors.toSet());
        //     List<Thumb> thumbList = Db.lambdaQuery(Thumb.class)
        //             .eq(Thumb::getUserId, loginUser.getId())
        //             .in(Thumb::getBlogId, blogIdSet)
        //             .list();
        //     // List<Thumb> thumbList = thumbService.lambdaQuery()
        //     //         .eq(Thumb::getUserId, loginUser.getId())
        //     //         .in(Thumb::getBlogId, blogIdList)
        //     //         .list();   // 获取点赞
        //     thumbList.forEach(thumb -> blogIdHasThumbMap.put(thumb.getBlogId(), true));
        // }

        // 直接查询 Redis
        if (ObjUtil.isNotEmpty(loginUser)) {
            List<Object> blogIdList = blogList.stream().map(blog -> blog.getId().toString()).collect(Collectors.toList());
            // 获取点赞
            // List<Object> thumbList = redisTemplate.opsForHash().multiGet(
            //         ThumbConstant.USER_THUMB_KEY_PREFIX + loginUser.getId(), blogIdList);

            // 获得点赞列表 (userId) -> (blogId, thumbId)
            List<Object> thumbList = redisTemplate.opsForHash().multiGet(
                     RedisKeyUtil.getUserThumbKey(loginUser.getId()), blogIdList);

            thumbList.stream().filter(ObjUtil::isNotNull).forEach(thumb ->
                blogIdHasThumbMap.put(Long.valueOf(thumb.toString()), true));
        }

        return blogList.stream()
                .map(blog -> {
                    BlogVo blogVO = BeanUtil.copyProperties(blog, BlogVo.class);
                    blogVO.setHasThumb(blogIdHasThumbMap.get(blog.getId()));
                    return blogVO;
                })
                .toList();
    }
}




